﻿namespace AiFrame.InterfaceLib.Data.Access
{
    /// <summary>
    /// A basic Dao factory.
    /// </summary>
    public class BasicDaoFactory<T> where T : new()
    {
        /// <summary>
        /// The database connection.
        /// </summary>
        private static IDatabaseConnection _databaseConnection;

        /// <summary>
        /// The instance of the type.
        /// </summary>
        private static T _instance;

        /// <summary>
        /// The protected constructor.
        /// </summary>
        protected BasicDaoFactory()
        {
        }

        /// <summary>
        /// Gets or sets the database connection.
        /// </summary>
        public static IDatabaseConnection DatabaseConnection
        {
            get { return _databaseConnection; }
            set
            {
                if (value == null)
                    throw new InvalidValueException(
                        "Die BasicDaoFactory darf mit keiner NULL-DatabaseConnection initialisiert werden.");

                _databaseConnection = value;
            }
        }

        /// <summary>
        /// Gets the instance of the dao factory.
        /// </summary>
        public static T Instance
        {
            get
            {
                if (_databaseConnection == null)
                    throw new MissingInitialisationException("Für die BasicFactory muss eine Session angegeben werden.");

                if (_instance == null)
                {
                    _instance = new T();
                }

                return _instance;
            }
        }

        /// <summary>
        /// Initializes the dao factory.
        /// </summary>
        /// <param name="databaseConnection"></param>
        public static void Initialize(IDatabaseConnection databaseConnection)
        {
            DatabaseConnection = databaseConnection;
        }
    }
}